<template>
  <div class="sse">
    <div class="status">
      <span class="status-indicator" :class="{ active: isConnected }"></span>
      <span class="status-text">{{ isConnected ? 'SSE 连接中...' : '已断开' }}</span>
      <span class="mechanism">机制：服务器单向推送，客户端被动接收</span>
    </div>
    
    <div class="message-box">
      <h3>推送历史：</h3>
      <div class="message-list">
        <div 
          v-for="(item, index) in messageList" 
          :key="index" 
          class="message-item"
          :class="{ 'new-message': index === messageList.length - 1 && isConnected }"
        >
          {{ item }}
        </div>
        <div v-if="messageList.length === 0" class="empty-message">
          等待服务器推送...
        </div>
      </div>
    </div>
    
    <div class="controls">
      <button 
        @click="toggleSSE" 
        :class="{ active: isConnected }"
        class="toggle-btn"
      >
        {{ isConnected ? '断开连接' : '建立连接' }}
      </button>
    </div>
    
    <div class="stats">
      <div class="stat-item">
        <span class="stat-label">推送次数：</span>
        <span class="stat-value">{{ messageList.length }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">连接状态：</span>
        <span class="stat-value" :class="{ connected: isConnected }">
          {{ isConnected ? '已连接' : '未连接' }}
        </span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'

const messageList = ref(['等待服务器推送...'])
const isConnected = ref(false)
let eventSource = null

// 建立/断开 SSE 连接
const toggleSSE = () => {
  if (isConnected.value) {
    // 断开连接
    eventSource?.close()
    eventSource = null
    isConnected.value = false
    messageList.value.push('已断开 SSE 连接')
  } else {
    // 建立连接（使用 Nest.js 内置 SSE 接口）
    eventSource = new EventSource('http://localhost:3000/sse/data')
    
    // 监听正常推送（type: 'message'）
    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data)
      messageList.value.push(data.message)
      // 只保留最近10条记录，避免页面卡顿
      if (messageList.value.length > 10) {
        messageList.value.shift()
      }
    }

    // 监听自定义事件类型（可选）
    eventSource.addEventListener('customEvent', (event) => {
      messageList.value.push(`自定义事件：${event.data}`)
    })

    // 监听连接错误
    eventSource.onerror = (error) => {
      console.error('SSE 连接错误：', error)
      messageList.value.push('SSE 连接异常，已断开')
      isConnected.value = false
      eventSource.close()
    }

    // 监听连接成功
    eventSource.onopen = () => {
      isConnected.value = true
      messageList.value.push('已建立 SSE 连接')
    }
  }
}

// 组件挂载时建立连接
toggleSSE()

// 组件卸载时断开连接
onUnmounted(() => {
  eventSource?.close()
})
</script>

<style scoped>
.sse {
  padding: 0;
}

.status {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #17a2b8;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #dc3545;
  transition: background-color 0.3s ease;
}

.status-indicator.active {
  background: #17a2b8;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.status-text {
  font-weight: 500;
  color: #2c3e50;
}

.mechanism {
  margin-left: auto;
  font-size: 0.85rem;
  color: #666;
}

.message-box {
  margin: 20px 0;
  padding: 20px;
  background: #fff;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.message-box h3 {
  color: #2c3e50;
  margin-bottom: 12px;
  font-size: 1.1rem;
}

.message-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 8px;
}

.message-item {
  margin: 8px 0;
  padding: 8px 12px;
  background: #fff;
  border-radius: 6px;
  border-left: 3px solid #17a2b8;
  font-size: 0.9rem;
  line-height: 1.4;
  transition: all 0.3s ease;
}

.message-item.new-message {
  background: #e3f2fd;
  border-left-color: #2196f3;
  animation: highlight 1s ease-out;
}

@keyframes highlight {
  0% { background: #bbdefb; }
  100% { background: #e3f2fd; }
}

.empty-message {
  text-align: center;
  color: #6c757d;
  font-style: italic;
  padding: 20px;
}

.controls {
  text-align: center;
  margin: 20px 0;
}

.toggle-btn {
  padding: 12px 24px;
  font-size: 1rem;
  font-weight: 500;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #6c757d;
  color: white;
  min-width: 120px;
}

.toggle-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.toggle-btn.active {
  background: linear-gradient(45deg, #17a2b8, #138496);
}

.stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-top: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-label {
  font-size: 0.85rem;
  color: #6c757d;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 1.1rem;
  font-weight: 600;
  color: #2c3e50;
}

.stat-value.connected {
  color: #17a2b8;
}

@media (max-width: 480px) {
  .stats {
    grid-template-columns: 1fr;
  }
  
  .status {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .mechanism {
    margin-left: 0;
  }
}
</style> 